#!/bin/bash
# 菜单导入V2错误处理测试脚本
# 验证统一错误数据结构和错误报告生成

set -e

echo "=== 菜单导入V2错误处理测试开始 ==="
echo "时间: $(date)"

# 配置
BASE_URL="http://localhost:3001"
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1Njk5NDExNywiZXhwIjoxNzU3MDgwNTE3LCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.kz4cuvnqVjzTJtMmh582rX-VPzTEWdmTHksEoVf0nFU"
TEST_DIR="/tmp/menu_import_error_test"

# 创建测试目录
mkdir -p $TEST_DIR
cd $TEST_DIR

echo "\n=== 测试1: 验证阶段错误处理 ==="
echo "1.1 测试缺少文件上传"
curl -sS -X POST $BASE_URL/api/menu-import/v2/validate \
  -H "Authorization: Bearer $TOKEN" \
  --max-time 30 > validate_no_file.json
echo "✓ 无文件上传测试完成"
echo "响应内容:"
cat validate_no_file.json | jq .

echo "\n1.2 测试文件过大（模拟）"
# 创建一个大文件来测试
dd if=/dev/zero of=large_file.xlsx bs=1M count=15 2>/dev/null
curl -sS -X POST $BASE_URL/api/menu-import/v2/validate \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@large_file.xlsx" \
  --max-time 30 > validate_large_file.json
echo "✓ 大文件测试完成"
echo "响应内容:"
cat validate_large_file.json | jq .

echo "\n=== 测试2: 正常流程获取job_id ==="
echo "2.1 下载模板并上传测试"
curl -sS $BASE_URL/api/menu-import/v2/template/menu.xlsx \
  -H "Authorization: Bearer $TOKEN" \
  -o test_template.xlsx --max-time 30

echo "2.2 上传模板进行验证"
curl -sS -X POST $BASE_URL/api/menu-import/v2/validate \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@test_template.xlsx" \
  --max-time 30 > validate_success.json
echo "✓ 模板验证完成"

# 提取job_id
JOB_ID=$(cat validate_success.json | jq -r '.job_id')
echo "获取到任务ID: $JOB_ID"

if [ "$JOB_ID" = "null" ] || [ -z "$JOB_ID" ]; then
  echo "❌ 无法获取有效的job_id，跳过后续测试"
  echo "验证响应:"
  cat validate_success.json | jq .
else
  echo "\n=== 测试3: 提交阶段错误处理 ==="
  echo "3.1 测试无效job_id"
  curl -sS -X POST "$BASE_URL/api/menu-import/v2/commit?job_id=invalid-job-id" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{}' --max-time 30 > commit_invalid_job.json
  echo "✓ 无效job_id测试完成"
  echo "响应内容:"
  cat commit_invalid_job.json | jq .
  
  echo "\n3.2 测试缺少job_id参数"
  curl -sS -X POST "$BASE_URL/api/menu-import/v2/commit" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{}' --max-time 30 > commit_no_job_id.json
  echo "✓ 缺少job_id测试完成"
  echo "响应内容:"
  cat commit_no_job_id.json | jq .
  
  echo "\n3.3 等待验证完成并测试正常提交"
  # 轮询等待验证完成
  for i in {1..10}; do
    echo "轮询第 $i 次，检查验证状态..."
    curl -sS $BASE_URL/api/menu-import/v2/jobs/$JOB_ID \
      -H "Authorization: Bearer $TOKEN" \
      --max-time 10 > "job_status_$i.json"
    
    STATUS=$(cat "job_status_$i.json" | jq -r '.job.status')
    echo "当前状态: $STATUS"
    
    if [ "$STATUS" = "validated" ] || [ "$STATUS" = "failed" ]; then
      echo "✓ 验证完成，状态: $STATUS"
      break
    fi
    
    sleep 2
  done
  
  # 检查最终状态
  FINAL_STATUS=$(cat "job_status_$i.json" | jq -r '.job.status')
  if [ "$FINAL_STATUS" = "validated" ]; then
    echo "\n3.4 测试正常提交（第一次）"
    curl -sS -X POST "$BASE_URL/api/menu-import/v2/commit?job_id=$JOB_ID" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{}' --max-time 30 > commit_first.json
    echo "✓ 第一次提交完成"
    echo "响应内容:"
    cat commit_first.json | jq .
    
    echo "\n3.5 测试重复提交（幂等性）"
    curl -sS -X POST "$BASE_URL/api/menu-import/v2/commit?job_id=$JOB_ID" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -d '{}' --max-time 30 > commit_duplicate.json
    echo "✓ 重复提交测试完成"
    echo "响应内容:"
    cat commit_duplicate.json | jq .
  else
    echo "❌ 验证未成功，最终状态: $FINAL_STATUS"
    echo "最终任务信息:"
    cat "job_status_$i.json" | jq .
  fi
fi

echo "\n=== 测试4: 任务状态查询 ==="
if [ "$JOB_ID" != "null" ] && [ -n "$JOB_ID" ]; then
  echo "4.1 查询任务最终状态"
  curl -sS $BASE_URL/api/menu-import/v2/jobs/$JOB_ID \
    -H "Authorization: Bearer $TOKEN" \
    --max-time 10 > final_job_status.json
  echo "✓ 任务状态查询完成"
  
  echo "\n任务摘要信息:"
  cat final_job_status.json | jq '.job | {status, phase, summary, error_report_url}'
  
  # 检查是否有错误报告URL
  ERROR_REPORT_URL=$(cat final_job_status.json | jq -r '.job.error_report_url')
  if [ "$ERROR_REPORT_URL" != "null" ] && [ -n "$ERROR_REPORT_URL" ]; then
    echo "\n4.2 下载错误报告"
    curl -sS $BASE_URL$ERROR_REPORT_URL \
      -H "Authorization: Bearer $TOKEN" \
      -o error_report.csv --max-time 30
    echo "✓ 错误报告下载完成"
    
    if [ -f error_report.csv ] && [ -s error_report.csv ]; then
      echo "错误报告内容预览:"
      head -10 error_report.csv
    else
      echo "⚠️ 错误报告文件为空或不存在"
    fi
  else
    echo "ℹ️ 无错误报告URL（可能验证成功）"
  fi
fi

echo "\n=== 测试完成 ==="
echo "测试结果保存在: $TEST_DIR"
echo "主要文件:"
ls -la *.json *.csv *.xlsx 2>/dev/null || echo "部分文件可能不存在"

echo "\n=== 验收检查 ==="
echo "1. 验证阶段错误: $([ -f validate_no_file.json ] && echo '✓ 有响应' || echo '✗ 无响应')"
echo "2. 提交阶段错误: $([ -f commit_invalid_job.json ] && echo '✓ 有响应' || echo '✗ 无响应')"
echo "3. 任务状态查询: $([ -f final_job_status.json ] && echo '✓ 有响应' || echo '✗ 无响应')"
echo "4. 错误数据结构: $([ -f validate_no_file.json ] && cat validate_no_file.json | jq -e '.phase and .summary and .errors' >/dev/null 2>&1 && echo '✓ 结构正确' || echo '✗ 结构异常')"

echo "\n测试完成时间: $(date)"